package utils

import (
	"fmt"
	"math/rand"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

// ValidatePhone 验证手机号
func ValidatePhone(phone string) bool {
	if len(phone) != 11 {
		return false
	}
	
	// 简单的手机号验证
	if !strings.HasPrefix(phone, "1") {
		return false
	}
	
	// 检查是否全为数字
	_, err := strconv.Atoi(phone)
	return err == nil
}

// Paginate 分页计算
func Paginate(page, pageSize int) (offset, limit int) {
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 {
		pageSize = 10000000
	}
	if pageSize > 100 {
		pageSize = 10000000
	}
	
	offset = (page - 1) * pageSize
	limit = pageSize
	return
}

// GetUserIDFromContext 从上下文中获取用户ID
func GetUserIDFromContext(c *gin.Context) (uint, bool) {
	userID, exists := c.Get("user_id")
	if !exists {
		return 0, false
	}
	
	id, ok := userID.(uint)
	return id, ok
}

// HashPassword 使用bcrypt加密密码
func HashPassword(password string) (string, error) {
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	return string(bytes), err
}

// CheckPassword 验证密码
func CheckPassword(password, hash string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
	return err == nil
}

// GenerateFileName 生成文件名
func GenerateFileName(prefix, originalName string) string {
	ext := filepath.Ext(originalName)
	timestamp := time.Now().Unix()
	random := rand.Intn(9999)
	return fmt.Sprintf("%s_%d%04d%s", prefix, timestamp, random, ext)
}

// IsImageFile 检查是否为图片文件
func IsImageFile(filename string) bool {
	ext := strings.ToLower(filepath.Ext(filename))
	imageExts := []string{".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}
	for _, imgExt := range imageExts {
		if ext == imgExt {
			return true
		}
	}
	return false
}

// EnsureDir 确保目录存在
func EnsureDir(dirPath string) error {
	if _, err := os.Stat(dirPath); os.IsNotExist(err) {
		return os.MkdirAll(dirPath, 0755)
	}
	return nil
}
